package com.lxu;

import java.io.File;

/**
 * 本实例采用锁的方式实现主内存和工作内存的数据一致性
 */
public class VolatileDemo2 {

    public static void main(String[] args) throws InterruptedException {

        MyThread myThread = new MyThread("multipleThread");
        myThread.start();

        while (true) {
            synchronized (myThread) {
                if (myThread.isFlag()) {
                    System.out.println("main进程读取到的Flag值为：" + myThread.isFlag());
                    break;
                }
            }
        }
    }


    static class MyThread extends Thread {
        private boolean flag = false;

        public MyThread(String threadName) {
            super(threadName);
        }

        public boolean isFlag() {
            return flag;
        }

        @Override
        public void run() {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            flag = true;
            if (flag) {
                System.out.println("子线程已经成功修改了Flag的值，Flag为：" + flag);
            }
        }
    }
}
